<template>
  <div class="divBox">
    <base-info :viewData="viewData" ref="baseInfo"/>
    <el-card class="box-card">

      <el-form size="small" label-width="100px">
        <el-form-item label="缴费单类型：">
          <el-radio-group v-model="listPram.orderType" type="button" @change="seachList">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button label="1">房租缴费 </el-radio-button>
            <el-radio-button label="2">保证金缴费 </el-radio-button>
            <el-radio-button label="3">滞纳金缴费</el-radio-button>
            <el-radio-button label="4">物业费缴费 </el-radio-button>
            <el-radio-button label="5">组合缴费</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="支付状态：">
          <el-radio-group v-model="listPram.payStatus" type="button" @change="seachList">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button label="1">已支付 </el-radio-button>
            <el-radio-button label="0">未支付 </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="开票状态：">
          <el-radio-group v-model="listPram.invoiceStatus" type="button" @change="seachList">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button label="1">已开票 </el-radio-button>
            <el-radio-button label="0">未开票 </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="收据状态：">
          <el-radio-group v-model="listPram.receiptStatus" type="button" @change="seachList">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button label="0">已生成</el-radio-button>
            <el-radio-button label="1">未生成</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="房屋类型：">
          <el-radio-group v-model="listPram.houseType" type="button"  size="small"  @change="seachList">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button v-for="(item,i) in houseTypeOptions" :key="i" :label="item.id">{{ item.houseTypeName }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="房屋:">
          <el-input v-model="listPram.fwkeyword" placeholder="请输入租赁证编号、地址关键词" clearable style="width: 400px"/>
        </el-form-item>
        <el-form-item label="承租人:">
          <el-input v-model="listPram.yhkeyword" placeholder="姓名、身份证号、手机号关键词" clearable style="width: 400px"/>
        </el-form-item>
        <el-form-item label="缴费时间段:">
          <el-date-picker
              v-model="payTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="支付时间段:">
          <el-date-picker
              v-model="orderPayTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="订单号:">
          <el-input v-model="listPram.yhkeyword" placeholder="请输入订单号" clearable style="width: 400px"/>
          <el-button icon="el-icon-search" size="mini" type="primary" @click.native="handleSearch" style="margin-left: 10px">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          <el-button  class="el-form-item-align-right"
              icon="el-icon-upload2"
              @click="handleExport('multi')"
              type="primary" size="mini" v-has-permi="['admin:house:information:export']">批量导出
          </el-button>
        </el-form-item>

      </el-form>

      <el-table :data="listData.list" size="mini"
                :header-cell-style=" {fontWeight:'bold',background:'#f8f8f9',color: '#515a6e',height:'40px'}" border>
        <el-table-column type="expand" align="center" width="40">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand" label-width="190px" style="margin-left: 50px;">
              <el-form-item label="所属房屋：">
                <span>{{ props.row.houseDirection }}</span>
              </el-form-item>
              <el-form-item label="地段：">
                <span>{{ props.row.structureType }}</span>
              </el-form-item>
              <el-form-item label="楼层：">
                <span>{{ props.row.balconyBuildingArea }}/{{ props.row.balconyUsableArea }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column align="center"
                         type="selection"
                         width="50">
        </el-table-column>
        <el-table-column align="center" label="ID" prop="id" width="40"></el-table-column>
        <el-table-column align="center" label="缴费单号"  prop="orderId" width="100">
        </el-table-column>
        <el-table-column align="center" label="订单类型" prop="orderType" width="60"/>
        <el-table-column align="center" label="用户" width="90">
          <template slot-scope="scope">
<!--            //todo  跳转到用户详情页面 靠什么跳转  userId？-->
            <div @click="toUserDetail(scope.row.userId)" style="cursor: pointer; display: flex; align-items: center;">
              <!-- 头像（使用 el-avatar 或 img） -->
              <el-avatar
                  :size="30"
                  :src="imageUrl+scope.row.userFaceUrl"
                  style="margin-right: 10px;"
              ></el-avatar>
              <!-- 昵称 -->
              <span class="clickable-link">{{ scope.row.userNmae ||'-'}}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="关联房屋" width="140">
          <template slot-scope="scope">
            <div @click="handleHouse(scope.row.idValue)" class="clickable-link" style="display: flex; align-items: center;">
              <span>{{ scope.row.leaseCertificateNumberNew }}</span>
              <img
                  v-if="scope.row.houseType"
                  :src="getHouseTypeIcon(scope.row.houseType)"
                  style="width: 16px; height: 16px;"
                  :alt="scope.row.houseType"
              />
              <span>{{ scope.row.areaName }}-{{ scope.row.streetName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="关联承租人"  width="60">
          <template slot-scope="scope">
            <span @click="handleLessee(scope.row.currentTenantName)" class="clickable-link">
              {{ scope.row.currentTenantName }}_{{ scope.row.currentTenantIdCardLastFour }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="收费标准" header-align="center">
          <el-table-column align="center" label="应收" prop="beforeAdjustment" width="50"/>
          <el-table-column align="center" label="实收（调差后）" prop="afterAdjustment" min-width="50"/>
        </el-table-column>
        <el-table-column align="center" label="计费面积" prop="calculatedArea" width="50"/>
        <el-table-column align="center" label="缴费时段" min-width="80">
          <template slot-scope="scope">
            <span v-if="['房租缴纳', '物业费缴费', '滞纳金缴费'].includes(scope.row.orderType)">
              {{ scope.row.fwPayTime }}至{{ scope.row.fwUntilPayTime }}
            </span>
            <span v-else-if="scope.row.orderType === '保证金缴纳'">-</span>
            <span v-else>{{ scope.row.fwPayTime }}至{{ scope.row.fwUntilPayTime }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="应缴金额" prop="actuallyPaidAmount" width="50">
          <template slot-scope="scope" >
              <span @click="showFormula(scope.row)" class="clickable-link">
                ￥{{ scope.row.actuallyPaidAmount || 0}}
              </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="实付金额" prop="actuallyPaidAmount" width="50"/>
        <el-table-column align="center" label="经办人" prop="realName" min-width="50"/>
        <el-table-column align="center" label="支付凭证" prop="paymentVoucher" min-width="50"/>
        <el-table-column align="center" label="支付时间" prop="payTime" min-width="60"/>
        <el-table-column align="center" label="支付方式" prop="paymentType" min-width="60">
          <template slot-scope="scope">
            {{
              {1: '在线缴费', 2: '扫码缴费', 3: '线下现金缴费'}[scope.row.paymentType] || '未知支付方式'
            }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="支付状态" prop="payStatus" width="50">
          <template slot-scope="scope">
            {{
              {0: '未支付', 1: '已支付'}[scope.row.payStatus] || '未知支付状态'
            }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="收据状态" prop="receiptUrl" width="50">
          <template slot-scope="scope">
            {{ scope.row.receiptUrl ? '已生成' : '未生成' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="开票状态" prop="invoiceUrl" width="50">
          <template slot-scope="scope">
            {{ scope.row.invoiceUrl ? '已生成' : '未生成' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="330" fixed="right">
          <template slot-scope="scope">
            <el-button icon="el-icon-edit" size="mini" type="primary" @click="openEdit(1,scope.row)"
                       v-has-permi="['admin:payment:detail']">查看收据
            </el-button>
            <el-button icon="el-icon-edit" size="mini" type="primary" @click="openEdit(1,scope.row)"
                       v-has-permi="['admin:payment:detail']">开票
            </el-button>
            <el-button icon="el-icon-edit" size="mini" type="primary" @click="openDetail(scope.row.id)"
                       v-has-permi="['admin:payment:detail']">订单详情
            </el-button>
            <el-button icon="el-icon-edit" size="mini" type="primary" @click="openRecord(scope.row)"
                       v-has-permi="['admin:payment:detail']">订单记录
            </el-button>
            <el-button icon="el-icon-edit" size="mini" type="primary" @click="openEdit(1,scope.row)"
                       v-has-permi="['admin:payment:detail']">上传凭证
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          :current-page="listPram.page"
          :page-sizes="[10,20,40,60,80,100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="listData.count"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-card>

    <el-dialog
        :visible.sync="editDialog.visible"
        :title="editDialog.isCreate === 0? '编辑':'新增'"
        destroy-on-close
        :close-on-click-modal="false"
        top="50px"
        width="1200px">
      <edit
          v-if="editDialog.visible"
          :is-create="editDialog.isCreate"
          :edit-data="editDialog.editDate"
          @hideEditDialog="hideEditDialog"
          ref="editForm"
      />
    </el-dialog>

    <el-dialog
        :visible.sync="detailDialog.visible"
        title="订单详情"
        destroy-on-close
        :close-on-click-modal="false"
        top="50px"
        width="1200px">
      <detail
          v-if="detailDialog.visible"
          :id="detailDialog.id"
          @hideEditDialog="hideEditDialog"
          ref="editForm"
      />
    </el-dialog>

    <el-dialog title="月租金计算公式" :visible.sync="dialogVisible2" width="50%">
      <div>
        <p><strong>计算公式：</strong>应交月租金 = 使用面积 x 调差后收费标准</p>
        <div v-if="currentRow2">
          <p style="margin-top: 10px;margin-left: 145px"  > =
            {{currentRow2.usableArea || 0}} x {{currentRow2.calculatedPrice || 0}} = ￥{{currentRow2.totalPrice || 0}}
          </p>
        </div>
      </div>
    </el-dialog>


    <!--记录-->
    <el-dialog
        title="操作记录"
        :visible.sync="dialogVisibleJI"
        width="700px"
    >
      <el-table
          v-loading="LogLoading"
          border
          :data="tableDataLog.data"
          style="width: 100%"
      >
        <el-table-column
            prop="oid"
            align="center"
            label="ID"
            min-width="80"
        />
        <el-table-column
            prop="changeMessage"
            label="操作记录"
            align="center"
            min-width="280"
        />
        <el-table-column
            prop="createTime"
            label="操作时间"
            align="center"
            min-width="280"
        />
      </el-table>
      <div class="block">
        <el-pagination
            :page-sizes="[10, 20, 30, 40]"
            :page-size="tableFromLog.limit"
            :current-page="tableFromLog.page"
            layout="total, sizes, prev, pager, next, jumper"
            :total="tableDataLog.total"
            @size-change="handleSizeChangeLog"
            @current-change="pageChangeLog"
        />
      </div>
    </el-dialog>




  </div>
</template>

<script>
import edit from './edit.vue'
import detail from './detail.vue'
import {amountDeleteRow, getPaymentOrderTopStatistics, recordList} from "@/api/payment";
import {checkPermi} from "@/utils/permission";
import {getAdminGetFwlx} from "@/api/house";
import baseInfo from "@/views/dashboard/components/baseInfo.vue";
import {exportMultiColumn} from "@/api/export";

export default {
  components: {baseInfo, edit,detail},
  data() {
    return {
      listData: {
        list: [], count: 0
      },
      orderPayTime:[],
      payTime:[],
      listPram: {
        page: 1,
        limit: 10,
        fwkeyword: '',
        houseType: '',
        invoiceStatus: '',
        orderType : '',
        payStatus: '',
        orderPayEndTime: '',
        orderPayStartTime: '',
        payTime: '',
        untilPayTime: '',
        receiptStatus: '',
        yhkeyword: '',
      },
      editDialog: {
        visible: false,
        isCreate: 0, // 0=创建，1=编辑
        editDate: {},
      },
      detailDialog: {
        visible: false,
        id: null
      },
      dialogVisibleJI:false,
      tableDataLog: {
        data: [
          {
            oid: 1,
            changeMessage: "管理员修改了订单状态为已发货",
            createTime: "2023-05-02 15:30:45"
          },
          {
            oid: 2,
            changeMessage: "系统自动生成了订单",
            createTime: "2023-05-01 14:30:22"
          },
          // 可以添加更多记录...
        ],
        total: 2
      },
      tableFromLog: {
        page: 1,
        limit: 10,
        orderNo: 0
      },
      LogLoading:false,
      tableLoading: false,
      houseTypeOptions: [],
      viewData: {},
      imageUrl: '',
      dialogVisible2: false,
      currentRow2: null,

    }
  },
  mounted() {
    this.imageUrl = process.env.VUE_APP_IMAGE_URL
    this.getList()
    this.getHouseType()
    this.getTopStatistics();
  },
  methods: {
    checkPermi,
    getList() {
      this.tableLoading = true
      if (this.orderPayTime || this.payTime) {

        this.listPram.payTime = this.payTime[0]
        this.listPram.untilPayTime =  this.payTime[1]
        this.listPram.orderPayEndTime = this.orderPayTime[0]
        this.listPram.orderPayStartTime = this.orderPayTime[1]
      }
      recordList(this.listPram).then(res => {
        this.listData = res;
      }).finally(() => {
        this.tableLoading = false;
      })

    },
    getTopStatistics() {
      this.saveLoading = true;
      getPaymentOrderTopStatistics().then((res) => {
        this.viewData = res
        this.close();
      }).finally(() => {
        this.saveLoading = false
      })

    },
    getHouseType() {
      // 获取房屋类型
      getAdminGetFwlx().then((res) => {
        this.houseTypeOptions = res
      })
    },
    seachList() {
      this.listPram.page = 1
      this.getList()
    },
    openEdit(isCreate, editDate) {
      this.editDialog.editDate = editDate;
      this.editDialog.isCreate = isCreate;
      this.editDialog.visible = true
    },
    openDetail(id) {
      this.detailDialog.id = id;
      this.detailDialog.visible = true
    },
    // 订单记录
    openRecord(id) {
      this.dialogVisibleJI = true
      // this.LogLoading = true
      this.tableFromLog.orderNo = id
      // orderLogApi( this.tableFromLog ).then(res => {
      //   this.tableDataLog.data = res.list
      //   this.tableDataLog.total = res.total
      //   this.LogLoading = false
      // }).catch(() => {
      //   this.LogLoading = false
      // })
    },
    handlerDelete(id) {
      this.$confirm('确认删除该数据吗？').then(() => {
        const loading = this.$loading({text: '删除中', background: 'rgba(255,255,255,.5)'})
        amountDeleteRow(id).then(() => {
          this.$message.success('删除成功')
          this.getList()
        }).finally(() => {
          loading.close()
        })
      })
    },
    hideEditDialog() {
      this.editDialog.visible = false
      this.getList()
    },
    handleSizeChange(val) {
      this.listPram.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listPram.page = val
      this.getList()
    },
    handleHouse(currentHouse) {
      this.$router.push({
        path: '/house/information',
        query: {
          currentHouse: currentHouse // 携带当前承租人名称作为查询参数
        }
      });
    },
    handleLessee(name) {
      this.$router.push({
        path: '/lessee/index',
        query: {
          lesseeName: name // 携带当前承租人名称作为查询参数
        }
      });
    },
    resetQuery() {
      this.listPram.houseType = '';
      this.listPram.invoiceStatus = '';
      this.listPram.orderType = '';
      this.listPram.payStatus = '';
      this.listPram.orderPayEndTime = '';
      this.listPram.orderPayStartTime = '';
      this.listPram.payTime = '';
      this.listPram.untilPayTime = '';
      this.listPram.receiptStatus = '';
      this.listPram.yhkeyword = '';
      this.listPram.fwkeyword = '';
      this.listPram.page = 1;
      this.getList()
    },
    handleSearch() {
      this.listPram.page = 1;
      this.getList();
    },
    handleExport(){
      exportMultiColumn().then(() => {
      }).finally(() => {
      })
    },
    toUserDetail(userId) {

      // 方式1：通过路径跳转
      this.$router.push({
        path: '/user/index',
        query: {
          userId: userId
        }
      });
    },
    // 显示弹窗
    showFormula (row) {
      this.currentRow2 = row;
      this.dialogVisible2 = true;
    },
    getHouseTypeIcon(houseType) {
      const iconMap = {
        '廉租房': require('@/assets/imgs/lianzu.png'),
        '公租房': require('@/assets/imgs/gongzu.png'),
        '直管公房': require('@/assets/imgs/zhiguan.png')
      };
      return iconMap[houseType] || '';
    },
    pageChangeLog(page) {
      this.tableFromLog.page = page
      this.openRecord()
    },
    handleSizeChangeLog(val) {
      this.tableFromLog.limit = val
      this.openRecord()
    },


  }
}
</script>

<style scoped lang="scss">
.clickable-link {
  color: #1890ff;
  cursor: pointer;
  text-decoration: none;
}

.clickable-link:hover {
  text-decoration: underline;
  color: #1890ff;
}
</style>
